package top.tsyz.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public HandlerInterceptor authInterceptor() {
        return new AuthInterceptor();
    }
    
    @Bean
    public HandlerInterceptor logInterceptor() {
        return new LogInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册日志拦截器，对所有路径生效
        registry.addInterceptor(logInterceptor())
                .addPathPatterns("/**");
        
        // 注册权限拦截器，对API路径生效，排除登录相关路径
        registry.addInterceptor(authInterceptor())
                .addPathPatterns("/api/**")
                .excludePathPatterns("/api/auth/login", "/api/auth/register", "/api/public/**");
    }

    /**
     * 权限拦截器
     */
    public static class AuthInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            System.out.println("AuthInterceptor preHandle: " + request.getRequestURI());
            
            // 示例：检查请求头中是否包含token
            String token = request.getHeader("Authorization");
            if (token == null || token.isEmpty()) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("{\"code\": 401, \"message\": \"未授权访问\"}");
                return false;
            }
            
            // 实际项目中需要验证token的有效性
            // 这里简化处理，只检查是否存在
            return true;
        }

        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
            System.out.println("AuthInterceptor postHandle: " + request.getRequestURI());
        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
            System.out.println("AuthInterceptor afterCompletion: " + request.getRequestURI());
        }
    }

    /**
     * 日志拦截器
     */
    public static class LogInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            System.out.println("LogInterceptor preHandle: " + request.getRequestURI() + " at " + new Date());
            request.setAttribute("startTime", System.currentTimeMillis());
            return true;
        }

        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
            System.out.println("LogInterceptor postHandle: " + request.getRequestURI());
        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
            Long startTime = (Long) request.getAttribute("startTime");
            if (startTime != null) {
                long executeTime = System.currentTimeMillis() - startTime;
                System.out.println("LogInterceptor afterCompletion: " + request.getRequestURI() + " executeTime: " + executeTime + "ms");
            }
        }
    }
}
